/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-15 Time: 23:16
 *
 * 新建报修工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    ScrollView,
    TextInput,
    Image, Modal, Platform, BackHandler,PermissionsAndroid
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './CreateRepairWorkOrderScreen.Style';
import {
    COLOR_FOCUS,
    COLOR_HEADER_END, COLOR_HEADER_START, COLOR_LINK,
    COLOR_THEME, FONT_COLOR_SUB_TITLE,
    FONT_SIZE_TITLE
} from "../../../../constant/PHColors"
import AntDesign from "react-native-vector-icons/AntDesign"
import Entypo from "react-native-vector-icons/Entypo"
import DividingLineViewComponent from "../../../../component/DividingLineViewComponent/DividingLineViewComponent"
import BottomButtonView from "../../../../component/BottomButtonView/BottomButtonView"
import LinearGradient from "react-native-linear-gradient";
import {SaveRepairWorkOrder} from "./Actions"
import {FetchStatus} from "../../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../../configuration/ReturnStatus";
import {doGetRepairRecordNewDefault} from "./Actions"
import LoadingView from "../../../../component/LoadingView/LoadingView"
import {getDs} from "../DepartmentalRepairOrderScreen/Actions";
import {SCREEN_WIDTH} from "../../../../constant/PHScreen";
import {AudioRecorder, AudioUtils} from "react-native-audio";
import Sound from "react-native-sound";
import {AppRequestPath} from "../../../../configuration/AppConfig";
import {getStore} from "../../../../configuration/StoreConfiguration";
import User from "../../../../model/User/User";
import {API_UPLOADIMG_AUDIO} from "../../../../constant/API";
import {changeSweepOrderStatus} from "../../../../component/BottomButtonView/Actions";
import {doDisplayWarnMessage} from "../../../../component/Message/Action";

class CreateRepairWorkOrderScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        title: '新建报修工单'
    });

    //构造
    constructor(props) {
        super(props);
        this.state = {
            role:'无组别',
            roleModalVisible:false,
            checkModalVisible:false,
            area:'',
            area_sn:'',
            areaCheck:true,
            object:'',
            objectCheck:true,
            object_sn:'',
            remark:'',
            normalBtn:require("../../../../resource/login/dl_yixuan.png"),
            urgentBtn:require("../../../../resource/login/dl_weixuan.png"),
            type:'0',
            CacheRole:[],
            returnModalVisible:false,
            ifLocalPage:true,
            imageArr:[{},{},{},{},{}], //图片数组

            hasPermission: undefined, //授权状态
            audioPath: AudioUtils.DocumentDirectoryPath + '/test.aac', // 文件路径
            recording: false, //是否录音
            pause: false, //录音是否暂停
            stop: false, //录音是否停止
            currentTime: 0, //录音时长
            audioBase64:'',     //base64格式的音频文件
            soundState_c:'点击播放',
        }
    }

    componentWillReceiveProps(nextProps): void {
        let {dispatch} = this.props;

        if(nextProps.navigation.getParam("area")!==""&&typeof (nextProps.navigation.getParam("area"))!=='undefined'){
            this.setState({areaCheck: false,area:nextProps.navigation.getParam("area"),area_sn:nextProps.navigation.getParam("area_sn")});
        }else{
            this.setState({areaCheck: true});
        }

        if(nextProps.navigation.getParam("object")!==""&&typeof (nextProps.navigation.getParam("object"))!=='undefined'){

            let oldObject = this.state.object===""?"":this.state.object+",";
            let oldObjectSn = this.state.object_sn===""?"":this.state.object_sn+",";
            console.log(oldObjectSn)
            console.log(oldObject)
            this.setState({objectCheck: false,object:oldObject+nextProps.navigation.getParam("object"),object_sn:oldObjectSn+nextProps.navigation.getParam("object_sn")});
        }else{
            if(this.state.object===""){
                this.setState({objectCheck: true});
            }else{
                this.setState({objectCheck: false});
            }
        }

        if (nextProps.onCreateRepairWorkOrder !== this.props.onCreateRepairWorkOrder && nextProps.onCreateRepairWorkOrder.fetchStatus === FetchStatus.Success) {
            if (nextProps.onCreateRepairWorkOrder.RETURN === ReturnStatus.Success) {
                this.props.navigation.goBack();
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onCreateRepairWorkOrder.MSG))
            }
        }
    }

    componentDidMount() {
        let {dispatch} = this.props;
        // 获取新建维修单默认参数
        dispatch(doGetRepairRecordNewDefault());
        // 请求授权
        AudioRecorder.requestAuthorization()
            .then(isAuthor => {
                console.log('是否授权: ' + isAuthor)
                if(!isAuthor) {
                    return alert('请前往设置开启录音权限')
                }
                this.setState({hasPermission: isAuthor})
                this.prepareRecordingPath(this.state.audioPath);
                // 录音进展
                AudioRecorder.onProgress = (data) => {
                    this.setState({currentTime: Math.floor(data.currentTime)});
                };
                // 完成录音
                AudioRecorder.onFinished = (data) => {
                    // data 返回需要上传到后台的录音数据
                    console.log(this.state.currentTime)
                    console.log(data);
                    this.state.audioBase64 = data['base64']?data['base64']:'';
                };
            })
    };

    /**
     * AudioRecorder.prepareRecordingAtPath(path,option)
     * 录制路径
     * path 路径
     * option 参数
     */
    prepareRecordingPath = (path) => {
        const option = {
            SampleRate: 44100.0, //采样率
            Channels: 2, //通道
            AudioQuality: 'High', //音质
            AudioEncoding: 'aac', //音频编码
            OutputFormat: 'mpeg_4', //输出格式
            MeteringEnabled: false, //是否计量
            MeasurementMode: false, //测量模式
            AudioEncodingBitRate: 32000, //音频编码比特率
            IncludeBase64: true, //是否是base64格式
            AudioSource: 0, //音频源
        }
        AudioRecorder.prepareRecordingAtPath(path,option)
    }

    // 开始录音
    _record = async () => {
        if(!this.state.hasPermission) {
            return alert('没有授权')
        }
        if(this.state.recording) {
            return alert('正在录音中...')
        }
        if(this.state.stop) {
            this.prepareRecordingPath(this.state.audioPath)
        }
        this.setState({recording: true,pause: false})

        try {
            await AudioRecorder.startRecording()
        } catch (err) {
            console.log(err)
        }
    }

    // 暂停录音
    _pause = async () => {
        if(!this.state.recording) {
            return alert('当前未录音')
        }

        try {
            await AudioRecorder.pauseRecording()
            this.setState({pause: true, recording: false})
        } catch (err) {
            console.log(err)
        }
    }

    // 恢复录音
    _resume = async () => {
        if(!this.state.pause) {
            return alert('录音未暂停')
        }

        try {
            await AudioRecorder.resumeRecording();
            this.setState({pause: false, recording: true})
        } catch (err) {
            console.log(err)
        }
    }

    // 停止录音
    _stop = async () => {
        this.setState({stop: true, recording: false, paused: false});
        try {
            await AudioRecorder.stopRecording();
        } catch (error) {
            console.error(error);
        }
    }

    // 播放录音
    _play = async () => {
        let whoosh = new Sound(this.state.audioPath, '', (err) => {
            this.setState({soundState_c:"正在播放..."})
            if(err) {
                this.setState({soundState_c:"播放失败"})
                return console.log(err)
            }
            whoosh.play(success => {
                if(success) {
                    this.setState({soundState_c:"点击播放"})
                    console.log('success - 播放成功')
                }else {
                    this.setState({soundState_c:"播放失败"})
                    console.log('fail - 播放失败')
                }
            })
        })
    }


    componentWillMount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    onBackAndroid = () =>{
        if(this.state.roleModalVisible===false&&this.state.checkModalVisible===false&&this.state.ifLocalPage===true){
            this.setState({
                roleModalVisible:false,
                checkModalVisible:false,
                returnModalVisible:true,
            });
            return true;
        }else{
            return false;
        }
    };

  render(): React.ReactNode {
    let {dispatch, onCreateRepairWorkOrder} = this.props;
    let { stop, recording, pause, currentTime } = this.state;
    let _this = this;
    // if (onRepairRecordNewDefault.fetchStatus === FetchStatus.Start) {
    if (onCreateRepairWorkOrder.fetchStatus === FetchStatus.Start) {
      return <LoadingView/>
    } else
      return (
        <SafeAreaView style={styles.body}>
          <ScrollView style={styles.body}>

            <DividingLineViewComponent lineHeight={10}/>

          {/* 报修地点 */}
          <View style={{backgroundColor: '#FFF'}}>
            <TouchableOpacity activeOpacity={0.8} onPress={() => {
                _this.state.ifLocalPage=false;
                this.props.navigation.navigate('RepairWorkOrderChoosePlaceScreen',{"returnPage":'CreateRepairWorkOrderScreen',"type":"area","title":"地点","sn":_this.state.area_sn,goBack:(returnJson)=>{
                        _this.props.navigation.navigate('CreateRepairWorkOrderScreen',returnJson);
                        _this.state.ifLocalPage=true;
                    }})
            }}>
              <View style={styles.itemHeader}>
                <View style={styles.itemHeaderLeft}>
                  <Text style={styles.itemHeaderText}>
                    报修地点
                  </Text>
                  {
                    this.state.areaCheck &&
                    <AntDesign name={'exclamation'} size={15} style={{color: 'red', marginLeft: 10}}/>
                  }
                </View>
                <View style={styles.itemHeaderRight}>
                  <AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>
                </View>
              </View>
            </TouchableOpacity>

              <DividingLineViewComponent lineHeight={1}/>

            <View style={{margin: 15,flexDirection:'row'}}>
              <TextInput
                placeholder={'选择报修地点'}
                style={{
                  fontSize: 16,
                  padding: 0,
                  color:(this.state.area===""||typeof (this.state.area)==='undefined')?'#f1f1f1':'#000000',
                }}
                numberOfLines={1}
                underlineColorAndroid={'transparent'}
                onChangeText={text=>{
                  if(text===""){
                      this.setState({areaCheck:true,area: text});
                  }else{
                      this.setState({areaCheck:false,area: text});
                  }
                }}
                defaultValue = {this.state.area}
                editable = {false}
              />
                {
                    (this.state.area!==""&&typeof (this.state.area)!=='undefined') && (
                        <View style={styles.itemHeaderRight}>
                            <AntDesign name={'closecircle'} size={18} style={{color: '#d7d7d7'}} onPress={()=>{
                                this.setState({
                                    area: '',
                                    area_sn:'',
                                });
                                this.props.navigation.setParams({area:'',area_sn:''})
                            }}/>
                        </View>
                    )
                }
            </View>

            </View>

            <DividingLineViewComponent lineHeight={10}/>

          {/* 报修对象 */}
          {
            <View style={{backgroundColor: '#FFF'}}>
              <TouchableOpacity activeOpacity={0.8} onPress={() => {
                  _this.state.ifLocalPage=false;
                  this.props.navigation.navigate('RepairWorkOrderChoosePlaceScreen',{"returnPage":'CreateRepairWorkOrderScreen',"type":"object","title":"对象","sn":_this.state.object_sn,goBack:(returnJson)=>{
                          _this.props.navigation.navigate('CreateRepairWorkOrderScreen',returnJson);
                          _this.state.ifLocalPage=true;
                      }})
              }}>
                <View style={styles.itemHeader}>
                  <View style={styles.itemHeaderLeft}>
                    <Text style={styles.itemHeaderText}>
                      报修对象
                    </Text>
                    {
                      this.state.objectCheck &&
                      <AntDesign name={'exclamation'} size={15} style={{color: 'red', marginLeft: 10}}/>
                    }
                  </View>
                  <View style={styles.itemHeaderRight}>
                    <AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>
                  </View>
                </View>
              </TouchableOpacity>

                <DividingLineViewComponent lineHeight={1}/>

                {

                    this.state.object_sn!=="" ? this.state.object_sn.split(",").map((item, index) => {
                        return this.showObjectTextInput(item, index)
                    }) : (
                        <View style={{margin: 15,flexDirection:'row'}}>

                            <TextInput
                                placeholder={'选择报修对象'}
                                style={{
                                    fontSize: 16,
                                    padding: 0,
                                    color:(this.state.object===""||typeof (this.state.object)==='undefined')?'#f1f1f1':'#000000',
                                }}
                                numberOfLines={1}
                                underlineColorAndroid={'transparent'}
                                onChangeText={text=>{
                                    if(text===""){
                                        this.setState({objectCheck:true,object: text});
                                    }else{
                                        this.setState({objectCheck:false,object: text});
                                    }
                                }}
                                defaultValue = {this.state.object}
                                editable = {false}
                            />
                            {
                                (this.state.object!==""&&typeof (this.state.object)!=='undefined') && (
                                    <View style={styles.itemHeaderRight}>
                                        <AntDesign name={'closecircle'} size={18} style={{color: '#d7d7d7'}} onPress={()=>{

                                            this.setState({
                                                object: '',
                                                object_sn:'',
                                            });
                                            this.props.navigation.setParams({object:'',object_sn:''})
                                        }}/>
                                    </View>
                                )
                            }

                        </View>
                    )

                }

            </View>
          }

            <DividingLineViewComponent lineHeight={10}/>

          {
            <View style={{backgroundColor: '#FFF'}}>
              <View style={styles.itemHeader}>
                <View style={styles.itemHeaderLeft}>
                  <Text style={styles.itemHeaderText}>
                    备注信息
                  </Text>
                  {
                    false &&
                    <AntDesign name={'check'} size={14} style={{color: COLOR_THEME, marginLeft: 10}}/>
                  }
                </View>
                <View style={styles.itemHeaderRight}>
                  <Text style={{fontSize: 16, color: FONT_COLOR_SUB_TITLE}}>
                      {this.state.remark.length}
                    <Text style={{fontSize: 16, color: FONT_COLOR_SUB_TITLE}}>
                      /100
                    </Text>
                  </Text>
                </View>
              </View>

                <DividingLineViewComponent lineHeight={1}/>

              <View style={{margin: 15, height: 120}}>
                <TextInput
                  placeholder={'输入备注信息'}
                  multiline={true}
                  maxLength={100}
                  style={{
                    fontSize: 16,
                    padding: 0,
                      height:120,
                      textAlignVertical: "top",
                      lineHeight:25,
                  }}
                  underlineColorAndroid={'transparent'}
                  onChangeText={text => {
                      if(text.length>100){
                          text = text.substring(0,100)
                      }
                      this.setState({
                          remark:text,
                      })
                  }}
                />
              </View>
            </View>
          }

            <DividingLineViewComponent lineHeight={10}/>

            {/* 报修组别 */}
            {
              <View style={{backgroundColor: '#FFF'}}>
                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                }}>
                  <View style={styles.itemHeader}>
                    <View style={styles.itemHeaderLeft}>
                      <Text style={styles.itemHeaderText}>
                        报修级别
                      </Text>
                      {
                        false &&
                        <AntDesign name={'check'} size={14} style={{color: COLOR_THEME, marginLeft: 10}}/>
                      }
                    </View>
                    <View style={styles.itemHeaderRight}>
                      {/*<AntDesign name={'right'} size={14} style={{color: FONT_COLOR_TITLE}}/>*/}
                    </View>
                  </View>
                </TouchableOpacity>

                <DividingLineViewComponent lineHeight={1}/>

              <View style={{margin: 15, height: 20, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center'}}>
                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                    this.setState({
                        type:'0',
                        normalBtn:require("../../../../resource/login/dl_yixuan.png"),
                        urgentBtn:require("../../../../resource/login/dl_weixuan.png"),
                    })
                }}>
                  <View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 120}}>
                    <Image style={{width: 18, height: 18}} source={this.state.normalBtn}/>
                    <Text style={{fontSize: 16, marginLeft: 15}}>
                      普通
                    </Text>
                  </View>
                </TouchableOpacity>
                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                    this.setState({
                        type:'1',
                        normalBtn:require("../../../../resource/login/dl_weixuan.png"),
                        urgentBtn:require("../../../../resource/login/dl_yixuan.png"),
                    })
                }}>
                  <View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 120}}>
                    <Image style={{width: 18, height: 18}} source={this.state.urgentBtn}/>
                    <Text style={{fontSize: 16, marginLeft: 15}}>
                      紧急
                    </Text>
                  </View>
                </TouchableOpacity>
              </View>
            </View>
          }

            <DividingLineViewComponent lineHeight={10}/>

          {
            <TouchableOpacity activeOpacity={0.8} onPress={() => {
                this.setState({
                    roleModalVisible:true
                })
            }}>
              <View style={{backgroundColor: '#FFF'}}>
                <View style={styles.itemHeader}>
                  <View style={styles.itemHeaderLeft}>
                    <Text style={styles.itemHeaderText}>
                      报修组别
                    </Text>
                  </View>
                  <View style={styles.itemHeaderRight}>
                    <Text style={styles.itemHeaderText}>
                        {this.state.role}
                    </Text>
                    <AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>
                  </View>
                </View>
              </View>
            </TouchableOpacity>
          }

          <DividingLineViewComponent lineHeight={10}/>

          {
              <TouchableOpacity activeOpacity={0.8} onPress={() => {
              }}>
                  <View style={{backgroundColor: '#FFF'}}>
                      <View style={styles.itemHeader}>
                          <View style={styles.itemHeaderLeft}>
                              <Text style={styles.itemHeaderText}>
                                  语音说明
                              </Text>
                          </View>
                          <View style={styles.itemHeaderRight}>
                              {/*<Text style={styles.itemHeaderText}>
                                  点击录音
                              </Text>*/}
                              {
                                  stop ? (
                                      <View style={{ flexDirection: 'row',margin: 0,}}>
                                          <TouchableOpacity activeOpacity={0.8} onPress={this._play}>
                                              <View style={{
                                              }}>
                                                  <Text style={{ color: COLOR_LINK}}>
                                                      {this.state.soundState_c}
                                                  </Text>
                                              </View>
                                          </TouchableOpacity>
                                          <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                              this.prepareRecordingPath(this.state.audioPath);
                                              this.setState({stop: false, recording: false, paused: false,currentTime:0});
                                          }}>
                                              <View style={{
                                                  marginLeft: 20,
                                              }}>
                                                  <Text style={{ color: '#999999'}}>
                                                      删除录音
                                                  </Text>
                                              </View>
                                          </TouchableOpacity>
                                      </View>
                                  ): (
                                      <TouchableOpacity activeOpacity={0.8} onPressIn={this._record} onPressOut={this._stop}>
                                          <View>
                                              <Text style={{ color: '#999999'}}>
                                                  {
                                                      recording ? '正在录音 时长'+currentTime+'S' :
                                                          pause ? '已暂停' : '按住说话'
                                                  }
                                              </Text>
                                          </View>
                                      </TouchableOpacity>
                                  )
                              }
                          </View>
                      </View>
                  </View>
              </TouchableOpacity>
          }

            <DividingLineViewComponent lineHeight={10}/>

            {
              <TouchableOpacity activeOpacity={0.8} onPress={() => {
                // 跳转到选择图片上传
                //this.props.navigation.navigate('RepairWorkOrderUploadImageScreen')
                  let _t=this;
                  this.props.navigation.navigate('RepairWorkOrderUploadImageScreen',{"imageArr":this.state.imageArr,goBack:(data)=>{
                          _t.props.navigation.navigate('CreateRepairWorkOrderScreen');
                          _t.setState({
                              imageArr:data
                          });
                      }})
              }}>
                <View style={{backgroundColor: '#FFF'}}>
                  <View style={styles.itemHeader}>
                    <View style={styles.itemHeaderLeft}>
                      <Text style={styles.itemHeaderText}>
                        图片说明
                      </Text>
                    </View>
                    <View style={styles.itemHeaderRight}>
                      <AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>
                    </View>
                  </View>
                </View>
              </TouchableOpacity>
            }

            <DividingLineViewComponent lineHeight={10}/>

          </ScrollView>

        <BottomButtonView title={'完成'} onSubmitClick={() => {
            this._onCheck()
        }}/>

          <Modal visible={this.state.roleModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
              <View style={styles.modalContainer} onPress={()=> this.onRequestClose()}>
                  <View style={styles.modalBody}>
                      <View style={styles.modalHeader}>
                          <Text style={styles.modalHeaderText}>
                              报修组别
                          </Text>
                      </View>
                      <ScrollView>
                          <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                this.setState({
                                    role:'无组别'
                                });
                                this.onRequestClose()
                          }}>
                              <View style={styles.boxBody} onPress={()=>{

                              }}>
                                  <View style={styles.top}>
                                      <View style={styles.topLeft}>
                                          <Text style={styles.topPointText}>
                                              无组别
                                          </Text>
                                      </View>
                                      <View style={styles.topRight}>
                                          {
                                              (this.state.role)==='无组别' &&
                                              <Entypo name={'check'} size={20} style={{color: COLOR_THEME, marginTop:7,marginRight: 10,fontWeight: 'bold'}}/>
                                          }
                                      </View>
                                  </View>
                              </View>
                          </TouchableOpacity>
                          {
                              this.props.onCacheRole.map((item, index) => {
                                  return this._renderRole(item, index)
                              })
                          }
                      </ScrollView>
                      <TouchableOpacity  onPress={()=> this.onRequestClose()}>
                          <LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={[COLOR_HEADER_START, COLOR_HEADER_END]} style={{
                              height: 44,
                              margin: 0,
                              justifyContent: 'center',
                              alignItems: 'center',
                              borderBottomLeftRadius:10,
                              borderBottomRightRadius:10,
                          }}>
                              <Text style={{fontSize: FONT_SIZE_TITLE, color: '#FFF'}}>
                                  返回
                              </Text>
                          </LinearGradient>
                      </TouchableOpacity>
                  </View>
              </View>
          </Modal>

          <Modal visible={this.state.checkModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
              <View style={styles.modalContainer} onPress={()=> this.onRequestClose()}>
                  <View style={styles.checkModalBody}>
                      <View style={styles.checkModalHeader}>
                          <Text style={styles.checkModalHeaderText}>
                              确认下单？
                          </Text>
                      </View>
                      <View style={styles.checkModalCenter}>
                          <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                              this.setState({
                                  checkModalVisible:false,
                              })
                          }}>
                              <Text style={{color:'black'}}>
                                  取消
                              </Text>
                          </TouchableOpacity>
                          <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                              this._onSubmitClick()
                          }}>
                              <Text style={{color:'white'}}>
                                  下单
                              </Text>
                          </TouchableOpacity>
                      </View>
                  </View>
              </View>
          </Modal>

        <Modal visible={this.state.returnModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
            <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={()=> this.onRequestClose()}>
                <View style={styles.modalContainer} onPress={()=> this.onRequestClose()}>
                    <View style={styles.checkModalBody}>
                        <View style={styles.checkModalHeader}>
                            <Text style={styles.checkModalHeaderText}>
                                放弃新建工单么？
                            </Text>
                        </View>
                        <View style={styles.checkModalCenter}>
                            <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                this.setState({
                                    returnModalVisible:false,
                                });
                                this.props.navigation.goBack();
                            }}>
                                <Text style={{color:'black'}}>
                                    放弃
                                </Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                this.setState({
                                    returnModalVisible:false,
                                })
                            }}>
                                <Text style={{color:'white'}}>
                                    继续新建
                                </Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        </Modal>
      </SafeAreaView>
    )
    }

    showObjectTextInput=(item, index)=>{
                return (
                    <View style={{margin: 15,flexDirection:'row'}}>

                        <TextInput
                            style={{
                                fontSize: 16,
                                padding: 0,
                                color:(this.state.object===""||typeof (this.state.object)==='undefined')?'#f1f1f1':'#000000',
                            }}
                            numberOfLines={1}
                            underlineColorAndroid={'transparent'}
                            defaultValue = {this.state.object.split(",")[index]}
                            editable = {false}
                        />
                        {
                            (this.state.object!==""&&typeof (this.state.object)!=='undefined') && (
                                <View style={styles.itemHeaderRight}>
                                    <AntDesign name={'closecircle'} size={18} style={{color: '#d7d7d7'}} onPress={()=>{
                                        let newObject = this.state.object.split(",");
                                        newObject.splice(index,1);
                                        let newObjectSn = this.state.object_sn.split(",");
                                        newObjectSn.splice(index,1);
                                        console.log(newObject.join(','))
                                        this.setState({
                                            object: newObject.join(','),
                                            object_sn:newObjectSn.join(','),
                                        });
                                        this.props.navigation.setParams({object:'',object_sn:''})
                                    }}/>
                                </View>
                            )
                        }

                    </View>
                )
    }

    //列表内容循环
    _renderRole = (item, index) => {
        return (
            <TouchableOpacity key={index} activeOpacity={0.8}  onPress={() => {
                this.setState({
                    role:item.role
                });
                this.onRequestClose()
            }}>
                <View style={styles.boxBody}>
                    <View style={styles.top}>
                        <View style={styles.topLeft}>
                            <Text style={styles.topPointText}>
                                {item.role}
                            </Text>
                        </View>
                        <View style={styles.topRight}>
                            {
                                (this.state.role)===(item.role) &&
                                <Entypo name={'check'} size={20} style={{color: COLOR_FOCUS, marginTop:7,marginRight: 10,fontWeight: 'bold'}}/>
                            }
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    _onCheck=()=>{
        if(this.state.area===""||typeof(this.state.area)==="undefined" ){
            this.setState({areaCheck: true});
            return
        }else{
            this.setState({areaCheck: false});
        }
        if(this.state.object===""||typeof(this.state.object)==="undefined"){
            this.setState({objectCheck: true});
            return
        }else{
            this.setState({objectCheck: false});
        }
        this.setState({
            checkModalVisible:true,
        })
    }

    _onSubmitClick=()=>{
        let str = {};
        str.area_sn = this.state.area_sn;
        str.object_sn = this.state.object_sn;
        str.remark = this.state.remark;
        str.role = this.state.role;
        str.urgent = this.state.type;
        str.need_review = "1";
        this.state.imageArr.map((item, index) => {
            if(item!=={}){
                str["pic"+(index+1)] = (item.path)
            }
        });

        this.setState({
            checkModalVisible:false,
        })

        this.props.navigation.setParams({object:'',object_sn:''})

        if(this.state.audioBase64!==''){
            let token = getStore().getState().onToken;
            User.getUser(user => {
                let data = new FormData();
                data.append('base64', this.state.audioBase64);
                data.append("token", token);
                data.append("prefix", "qms_repairOrderAudio");
                data.append("orderid", str.area_sn+"_"+str.object_sn);
                data.append("hotelId", user.hotelId);
                console.log("*************"+JSON.stringify(data))
                try {
                    fetch(AppRequestPath()+ API_UPLOADIMG_AUDIO, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'multipart/form-data;charset=utf-8'
                        },
                        body: data
                    }).then(function(response) {
                        return response.json();
                    }).then(data=>{
                        console.log("+++++++++++"+JSON.stringify(data))
                        str.sound = data.DATA[0].filename
                        let outJson = {"qms_repair":str,"arg":{"self_report":"true"}};
                        let {dispatch} = this.props;
                        dispatch(SaveRepairWorkOrder(JSON.stringify(outJson)));
                    })
                } catch (err) {
                    console.log(err)
                }
            })

        }else{
            let outJson = {"qms_repair":str,"arg":{"self_report":"true"}};
            // console.log(JSON.stringify(outJson))
            let {dispatch} = this.props;
            dispatch(SaveRepairWorkOrder(JSON.stringify(outJson)));
        }


    }

    onRequestClose(){
        this.setState({
            roleModalVisible: false,
            checkModalVisible:false,
            returnModalVisible:false,
        })
    }

}

const props = state => {
    return {
        onCacheRole: state.onCache.role,
        onCreateRepairWorkOrder : state.onCreateRepairWorkOrder,
        onRepairRecordNewDefault: state.onRepairRecordNewDefault, // 新建维修单默认参数
    }
};

export default CreateRepairWorkOrderScreen = connect(props)(CreateRepairWorkOrderScreen);
